import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @Author quan
 * @Description 演示HttpServletRequest中的InputStream getInputStream()方法
 * @Date 2023/6/23 20:45
 */
/**
 * 不成功
 */

@WebServlet("/calc_ajax_json")
public class Demo3_Calc_ByAjax_JsonServlet extends HttpServlet {
    //类属性
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //定义返回对象
        LinkedHashMap<String,Object> result = new LinkedHashMap<String, Object>();
        //设置返回值类型和编码格式
        resp.setContentType("application/json;charset=utf-8");

        //1、getInputStream用于读取请求的 body 内容. 返回一个 InputStream 对象
        ServletInputStream inputStream = req.getInputStream();
        //2、读取inputStream中的数据，读到数组中
        //（1）定义一个byte数组:长度是int getContentLength()以字节为单位返回请求主体的长度
        byte[] jsonByte = new byte[req.getContentLength()];
        //（2）将inputStream中的流数据读取到数组中
        inputStream.read(jsonByte);
        //3、将byte数组转化为String
        String reqStr = new String(jsonByte);
        //4、使用json工具类将字符串转化为对象：jackson
        HashMap<String,Object> reqMap = objectMapper.readValue("reqStr",HashMap.class);
//        System.out.println(reqMap);
        //5、接收数据
        Integer num1 =  (Integer) reqMap.get("num1");
        Integer num2 =  (Integer) reqMap.get("num2");
        //非空校验
        if(num1 == null||num2==null){
            result.put("code",-1);
            result.put("msg","非法参数");
            result.put("data","");
        }else{
            int sum = num1+num2;
            result.put("code",200);
            result.put("msg","成功");
            result.put("data",sum);
        }
        //返回数据
        resp.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
